package com.jxc.listener;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jxc.aop.LogInfoAop;
import com.jxc.aop.LogRef;
import com.jxc.service.ClassPathScanManager;
import com.jxc.util.Application;
import com.jxc.util.ConfigReload;

public class DefaultApplicationSetupListener implements ServletContextListener {

	private ServletContext servletConetxt;

	private final static Log logger = LogFactory
			.getLog(DefaultApplicationSetupListener.class);

	public ServletContext getServletConetxt() {
		return servletConetxt;
	}

	public void contextInitialized(ServletContextEvent servletContextEvent) {
        
		servletConetxt = servletContextEvent.getServletContext();
		Application.getInstance().setApplicationRealPath(
				servletConetxt.getRealPath("") + File.separatorChar);
		
		Application.getInstance().setApplicationContext(WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext()));
		initAop();
		init();
		
	}
	
	private void initAop() {
		Set<Class> sets = ClassPathScanManager.getClasses("com.jxc.action");
        for(Class clz:sets){
        	Method[] methods = clz.getMethods();
        	for(Method method:methods){
        		if(method.getAnnotation(LogInfoAop.class)!=null){
        			LogRef logRef = new LogRef();
        			logRef.setClassName(clz.getName());
        			logRef.setMethodName(method.getName());
        			logRef.setInfo(((LogInfoAop)method.getAnnotation(LogInfoAop.class)).info());
        			Application.getInstance().getLogRefs().add(logRef);
        		}
        	}
        }
		
	}

	private void init() {
		Application.getInstance().setProperties(new ConfigReload().getProp());
	}

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
	}

}
